import { FC, useEffect, useState } from 'react';
import { ProCard, ProFormCheckbox } from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';
import dayjs from 'dayjs';
import KLines from '../k-line';
import { RecognitionStrategyCN } from '@/constants/strategy';
import { formatChineseAmount } from '@/pages/quotationCopy/utils';
import { pushExclude } from '@/service/apis/exclude';
import { createMonitoring, deleteMonitoring } from '@/service/apis/monitoring';

const StockItem: FC = ({ klines, code, name, monitoring, renderColor }: any) => {
  const [value, setValue] = useState([]);

  const [monitor, setMonitor]: any = useState([]);

  useEffect(() => {
    setValue(monitoring?.recognitionStrategies);
    setMonitor(monitoring);
  }, [monitoring]);

  return (
    <ProCard key={code} className="mb-4 pr-4">
      <div className="text-base flex">
        <span className="text-base font-bold cursor-pointer">
          {name} {code}
        </span>
        <span className="ml-4">
          <span>换手率：</span>
          <span>{klines?.at(-1)?.turn}%</span>
        </span>
        <span className="ml-4">
          <span>流通市值：</span>
          <span>{formatChineseAmount(klines?.at(-1)?.cmv)}</span>
        </span>
      </div>
      <div className="my-4 flex items-center">
        <ProFormCheckbox.Group
          label="策略"
          noStyle
          name="recognitionStrategies"
          fieldProps={{
            value,
            onChange: (val) => {
              setValue(val);
            },
          }}
          options={Object.keys(RecognitionStrategyCN).map((key) => ({
            label: RecognitionStrategyCN[key],
            value: key,
          }))}
        />
        <Space className="ml-4">
          <Button
            type="primary"
            onClick={() => {
              createMonitoring({ code, weight: 100, recognitionStrategies: value }).then((res) => {
                setMonitor(res);
                message.success('添加成功');
              });
            }}
          >
            添加
          </Button>
          <Button
            type="primary"
            danger
            onClick={() => {
              if (monitor?.id) {
                deleteMonitoring(monitor?.id).then(() => {
                  setValue([]);
                  message.success('删除成功');
                });
              }
            }}
          >
            删除
          </Button>
          <Button
            onClick={async () => {
              await pushExclude({ code, date: dayjs().startOf('day').valueOf().toString() });
              message.success('排除成功');
            }}
          >
            排除
          </Button>
        </Space>
      </div>
      <KLines klines={klines} renderColor={renderColor} />
    </ProCard>
  );
};

export default StockItem;
